package edu.cdnu.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import edu.cdnu.common.constant.MessageConstatnt;
import edu.cdnu.common.dto.HomeworkDto;
import edu.cdnu.common.result.ResultEntity;
import edu.cdnu.config.FileUploadConfiguration;
import edu.cdnu.pojo.HomeworkStudentPojo;
import edu.cdnu.service.HomeworkService;
import edu.cdnu.utils.TypeConversionUtils;

@RestController
@RequestMapping("/homework")
public class HomeworkController {
	
	@Autowired
	private HomeworkService homeworkService;
	@Autowired
	private FileUploadConfiguration fileUploadConfiguration;
	
	/**
	 * 通过课程id查询课程任务列表
	 * @param courseId
	 * @return
	 */
	@GetMapping("/homeworkList/{courseId}")
	public ResultEntity<List<HomeworkDto>> selectHomeworkListByCourseId(@PathVariable String courseId){
		List<HomeworkDto> list = new ArrayList<>();
		homeworkService.selectHomeworkListByCourseId(Integer.valueOf(courseId)).forEach(item->{
			list.add(TypeConversionUtils.homeworkPojoToHomeworkDto(item));
		});
		if(list.size() > 0) {
			return ResultEntity.createSuccessResult(list);
		}
		return ResultEntity.createFailResult(MessageConstatnt.GET_INFO_FAIL);
	}
	
	/**
	 * 新增或者修改课程任务
	 * @param homeworkPojo
	 */
	@PostMapping("/addOrUpdateHomework")
	public ResultEntity<?> addOrUpdateHomework(@RequestBody HomeworkDto homeworkDto) {
		homeworkService.addOrUpdateHomework(TypeConversionUtils.homeworkDtoToHomeworkPojo(homeworkDto));
		return ResultEntity.createSuccessResult(null);
	}
	
	/**
	 * 通过id删除一个课程通知
	 * @param homeworkId
	 * @return
	 */
	@DeleteMapping("/deleteHomework/{homeworkId}")
	public ResultEntity<?> deleteHomeworkByHomeworkId(@PathVariable String homeworkId){
		homeworkService.deleteHomeworkByHomeworkId(Integer.valueOf(homeworkId));
		return ResultEntity.createSuccessResult(null);
	}
	
	/**
	 * 用于 发布任务 和 提交 的时候上传文件，返回文件地址
	 * 这里存的是本地地址，而不是网络地址，后面用静态资源服务器代理时换网络地址
	 * @param file
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/uploadAppendix")
	public ResultEntity<?> uploadAppendixReturnFilePath(@RequestParam("file") MultipartFile file) throws IOException{
		//读取配置的路径,没有配置则设置默认路径
		String path=fileUploadConfiguration.getUploadPath();
		if(path == null) {
			path="f:/upload";
		}//判断 是否 以/结尾，是则去掉
		else if("/".equals(path.substring(path.length()-1))){
			//去掉末尾的/
			path = path.substring(0,path.length() -1);
		}
		InputStream in= file.getInputStream();
		//获取上传的文件名  这里是全名，有后缀的
		String fileName=file.getOriginalFilename();
		
		//时间戳(文件名)
		Long time = System.currentTimeMillis();
		
		//这里是创建文件夹
		File f=new File(path+"/"+time);
		if(!f.exists()) {
			f.mkdirs();
		}
		
		//全rurl
        String url=path+"/"+time+"/"+fileName;
        
		//写文件
		OutputStream out=new FileOutputStream(url);
		byte[] bs=new byte[1024];
		int len=-1;
		while((len=in.read(bs))!=-1) {
			out.write(bs,0,len);
		}
		in.close();
		out.close();
		return ResultEntity.createSuccessResult(url);
	}
	
	@GetMapping("/homeworkStudent/{studentId}")
	public ResultEntity<HomeworkStudentPojo> selectHomeworkStudentPojoByHomeworkIdAndStudentId(@PathVariable Integer studentId,Integer homeworkId){
		if(studentId == null || homeworkId == null) {
			return ResultEntity.createFailResult(MessageConstatnt.GET_INFO_FAIL);
		}
		List<HomeworkStudentPojo> list=homeworkService.selectHomeworkListByHomeworkIdAndStudentId(homeworkId, studentId);
		if(list!=null&&list.size()>0) {
			return ResultEntity.createSuccessResult(list.get(0));
		}
		return ResultEntity.createSuccessResult(null);
	}
	
	/**
	 * 插入或修改一个 学生-作业 信息
	 * @param homeworkStudentPojo
	 */
	@PostMapping("/addOrUpdateHomeworkStudent")
	public ResultEntity<?> addOrUpdateHomeworkStudent(@RequestBody HomeworkStudentPojo homeworkStudentPojo) {
		// 课程任务的id和学生的id 都要有，必须条件
		if(homeworkStudentPojo.getHomeworkId()==null||homeworkStudentPojo.getStudentId()==null) {
			return ResultEntity.createFailResult(MessageConstatnt.PARAMETER_LACK);
		}
		homeworkService.insertOrUpdateHomeworkStudent(homeworkStudentPojo);
		return ResultEntity.createSuccessResult(null);
	}
	
	/**
	 * 根据课程任务id来查询参与该课程任务的列表
	 * @param homeworkId
	 * @return
	 */
	@GetMapping("/selectHomeworkStudentList/{homeworkId}")
	public ResultEntity<?> selectHomeworkStudentListByHomeworkId(@PathVariable Integer homeworkId){
		return ResultEntity.createSuccessResult(homeworkService.selectHomeworkStudentInfoListByHomeworkId(homeworkId)); 
	}
	
	/**
	 * 只修改分数
	 * @param map 必要参数 id,score；次要参数homework_id,student_id
	 * @return
	 */
	@PostMapping("/updateScore")
	public ResultEntity<?> updateHomeworkStudentScore(@RequestBody Map<String,Object> map){
		// 用这个修改
		HomeworkStudentPojo homeworkStudent = new HomeworkStudentPojo((int)map.get("id"),
				(int)map.get("homework_id"), (int)map.get("student_id"),
				null, (int)map.get("score"), null);
		
		homeworkService.insertOrUpdateHomeworkStudent(homeworkStudent);
		return ResultEntity.createSuccessResult(null);
	}
}
